from application.enumeration.StatusCodeEnum import StatusCodeEnum
from application.util.StringUtil import md5_encode, is_valid_url
from application.exception.BasicException import BasicException
from application.mapper.ImageMapper import ImageMapper
from application.model.ImageModel import ImageModel


async def add_image(image_url: str) -> str:
    """
    新增图片
    :param image_url: 图片URL
    :return: 图片MD5索引
    """
    if not is_valid_url(image_url):
        raise BasicException(status_code=StatusCodeEnum.BAD_REQUEST_ERROR.value, message="图片URL不合法！")
    md5_index: str = md5_encode(image_url)  # md5索引
    # 如果数据库中已存在该图片，则直接返回
    if not await ImageMapper.get_data_by_field(md5=md5_index):
        # 新增图片
        image_model: ImageModel = ImageModel(
            url=image_url,
            md5=md5_encode(image_url)
        )
        if not await ImageMapper.insert(data=image_model.to_dict()):
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, message="新增图片失败！")
    return md5_index


async def batch_add_image(image_list: list) -> list:
    """
    批量新增图片
    :param image_list: 图片URL列表
    :return: 图片MD5索引列表
    """
    result: list = []
    image_model_list: list = []
    for image_url in image_list:
        if not is_valid_url(image_url):
            raise BasicException(status_code=StatusCodeEnum.BAD_REQUEST_ERROR.value, message="图片URL不合法！")
        md5_index: str = md5_encode(image_url)  # md5索引
        result.append(md5_index)  # 添加md5索引到返回结果中
        # 如果数据库中已存在该图片，则跳过
        if await ImageMapper.get_data_by_field(md5=md5_index):
            continue
        image_model_list.append(ImageModel(url=image_url, md5=md5_encode(image_url)))
    # 批量新增
    if not await ImageMapper.batch_insert(model_list=image_model_list):
        raise BasicException(status_code=StatusCodeEnum.ERROR.value, message="批量新增图片失败！")
    return result
